<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>运动中...</title>
    <link rel="stylesheet" href="css/style.css" />
    <script src="js/message.js"></script>
</head>
<body>
    <div class="timer-container">
        <div class="timer-header">
            <span id="elapsed-time">00:00</span>
        </div>
        <div class="next-exercise">
            <span id="next-text"></span>
        </div>
        <div class="current-exercise">
            <div id="exercise-name">准备开始</div>
            <div id="countdown">00:30</div>
        </div>
        <button id="pause-resume">暂停</button>
        <p><small>按空格键可暂停/继续</small></p>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const planData = JSON.parse(localStorage.getItem('currentExercisePlan'));
            if (!planData) {
                messageplugin({ message: "没有找到运动计划！", type: "error" });
                window.location.href = 'index.html';
                return;
            }
            const { exercises, duration, rest } = planData;
            let index = 0; // 当前运动索引
            let isPaused = false; // 是否暂停
            let elapsedTotal = 0; // 总时间（包含准备、休息、运动）
            // 状态标志
            let isPreparing = true;   // 是否在准备阶段
            let isResting = false;    // 是否在休息阶段

            let prepareSeconds = 10;  // 准备时间固定为10秒
            let countdownSeconds = duration; // 倒计时秒数
            let restSeconds = rest; // 休息秒数

            const exerciseNameEl = document.getElementById('exercise-name');
            const countdownEl = document.getElementById('countdown');
            const nextTextEl = document.getElementById('next-text');
            const elapsedTimeEl = document.getElementById('elapsed-time');
            const pauseBtn = document.getElementById('pause-resume');

            /**
             * 格式化显示秒数
             * @param seconds 秒数
             * @returns {string}
             */
            function formatTime(seconds) {
                const mins = String(Math.floor(seconds / 60)).padStart(2, '0');
                const secs = String(seconds % 60).padStart(2, '0');
                return `${mins}:${secs}`;
            }

            function updateDisplay() {
                if (isPreparing) {
                    exerciseNameEl.textContent = "准备中...";
                    countdownEl.textContent = formatTime(prepareSeconds);
                    nextTextEl.textContent = `下一项：${exercises[0]}` || '下一项：无';
                } else if (isResting) {
                    exerciseNameEl.textContent = "休息中...";
                    countdownEl.textContent = formatTime(restSeconds);
                    const nextIndex = index + 1;
                    if (nextIndex === exercises.length - 1) {
                        // 倒数第二项休息时，提示“最后一项”
                        nextTextEl.textContent = `最后一项：${exercises[nextIndex]}`;
                    } else if (nextIndex < exercises.length) {
                        nextTextEl.textContent = `下一项：${exercises[nextIndex]}`;
                    } else {
                        nextTextEl.textContent = '加油！坚持！这已经是最后一项辣(≧∇≦)ﾉ👏';
                    }
                } else {
                    exerciseNameEl.textContent = exercises[index];
                    countdownEl.textContent = formatTime(countdownSeconds);
                    const nextIndex = index + 1;
                    if (nextIndex === exercises.length - 1) {
                        nextTextEl.textContent = `最后一项：${exercises[nextIndex]}`;
                    } else if (nextIndex < exercises.length) {
                        nextTextEl.textContent = `下一项：${exercises[nextIndex]}`;
                    } else {
                        nextTextEl.textContent = '加油！坚持！这已经是最后一项辣(≧∇≦)ﾉ👏';
                    }
                }
                elapsedTimeEl.textContent = formatTime(elapsedTotal);
            }

            function tick() {
                if (isPaused) return;
                elapsedTotal++; // 所有阶段都计入总时间
                if (isPreparing) {
                    if (prepareSeconds > 0) {
                        prepareSeconds--;
                    } else {
                        isPreparing = false;
                        countdownSeconds = duration;
                    }
                } else if (isResting) {
                    if (restSeconds > 0) {
                        restSeconds--;
                    } else {
                        // 休息结束
                        isResting = false;
                        index++; // 此时进入下一项
                        if (index < exercises.length) {
                            countdownSeconds = duration;
                        } else {
                            finishWorkout();
                            return;
                        }
                    }
                } else {
                    // 正在运动
                    if (countdownSeconds > 0) {
                        countdownSeconds--;
                    } else {
                        // 当前运动结束
                        if (index + 1 >= exercises.length) {
                            // 最后一项运动结束后，不再休息，直接完成
                            finishWorkout();
                            return;
                        } else {
                            // 进入休息
                            isResting = true;
                            restSeconds = rest;
                        }
                    }
                }
                updateDisplay(); // 每次 tick 都更新 UI
            }

            /**
             * 结束运动
             */
            function finishWorkout() {
                clearInterval(timerInterval);
                exerciseNameEl.textContent = "🎉 全部完成！太厉害辣！你是最棒的！👍( •̀ ω •́ )✧👏🤞🌹😘";
                countdownEl.textContent = "00:00";
                nextTextEl.textContent = '🎉全部完成🎉';
                const executingPlan = JSON.parse(localStorage.getItem('currentExercisePlan'));
                if (executingPlan && executingPlan.dateKey) {
                    let allPlans = JSON.parse(localStorage.getItem('dailyPlans')) || {};
                    const planIndex = executingPlan.planIndex;
                    if (allPlans[executingPlan.dateKey] && allPlans[executingPlan.dateKey][planIndex]) {
                        allPlans[executingPlan.dateKey][planIndex].completed = true;
                        localStorage.setItem('dailyPlans', JSON.stringify(allPlans));
                    }
                    window.opener && window.opener.postMessage({
                        type: 'EXERCISE_COMPLETED',
                        dateKey: executingPlan.dateKey,
                        planIndex: planIndex
                    }, '*');
                }
                // 等待10秒后关闭运动页面
                setTimeout(() => {
                    window.close();
                }, 10000);
            }

            // 初始化显示
            updateDisplay();
            // 启动定时器
            const timerInterval = setInterval(tick, 1000);
            // 暂停/继续按钮
            pauseBtn.addEventListener('click', () => {
                isPaused = !isPaused;
                pauseBtn.textContent = isPaused ? '继续' : '暂停';
            });
            // 空格键控制暂停/继续
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space') {
                    e.preventDefault();
                    pauseBtn.click();
                }
            });
        });
    </script>
</body>
</html>